﻿using ImageManager.Model;
using ImageManager.MyType;
using System.Reflection;

namespace ImageManager.DBAccess.AOP
{
    public class UniqueCheckAction<T> : IBeforeSaveAction<T> where T : BaseModel, new()
    {
        public void Handle(BeforeSaveEventArgs<T> arg)
        {
            var propList = typeof(T).GetProperties();
            foreach (var prop in propList)
            {
                var uniqueAttribute = prop.GetCustomAttribute<MyUniqueAttribute>();
                if (uniqueAttribute == null) continue;
                var val = prop.GetValue(arg.Data);
                if (val == null) continue;
                using (DbInstance dbInstance = new DbInstance())
                {
                    DbFuzzyQuery dbFuzzyQuery = new DbFuzzyQuery(dbInstance,typeof(T));
                    var exist = dbFuzzyQuery.Where(CondCollection.True().Eq(prop.Name, val).NotEq(nameof(BaseModel.Pk), arg.Data.Pk)).Count();
                    if (exist>0)
                    {
                        arg.Message = "存在重复值";
                        arg.Cancle = true;
                        return;
                    }
                }
            }

        }
    }
}
